public class VolatileDemo {
    // 测试变量：不加volatile
    private static int a = 0;
    // 加上volatile对比：private static volatile int a = 0;

    public static void main(String[] args) {
        // 线程1：每1秒递增a
        Thread incrementThread = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    a++; // 递增a
                    System.out.println("递增后 a = " + a);
                    Thread.sleep(1000); // 每1秒递增一次
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 线程2：死循环判断a是否等于10，等于则退出
        Thread checkThread = new Thread(() -> {
            System.out.println("开始等待a == 10...");
            while (a != 10) {
                // 空循环，持续判断
            }
            System.out.println("检测到a == 10，退出循环！");
        });

        // 启动两个线程
        checkThread.start();
        incrementThread.start();
    }
}